<?php
/**
 * Created by PhpStorm.
 * User: xiaolang
 * Date: 2018/3/13
 * Time: 10:05
 */

namespace App\Http\Controllers\Admin;


use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Http\Request;


class AuthController extends Controller 
{
    use ThrottlesLogins;

    /*
     * 后台登录
     */
    public function login()
    {
       return view('Admin.login'); 
    }

    public function username()
    {
        return 'email';
    }
    
    /*
     * 执行登录
     */
    public function doLogin(Request $request){
        $this->validate($request,['email' => 'required','password' => 'required'],[
            'email.required' => '账号不为空',
            'password.required' => '密码不为空',
        ]);

        if ($this->hasTooManyLoginAttempts($request)) {
            return $this->sendLockoutResponse($request);
        }
        $api = 'auth/login';
        $res = http_admin(['post', $api])->send($request->only('email','password'));
        if(0 == $res['code'] && array_get($res,'data.user')){
            session(['admin_user' => $res['data']['user']]);
            session(['is_super_admin' => $res['data']['user']['is_super_admin']]);
            session(['admin_user_id' => $res['data']['user']['admin_user_id']]);
            session(['admin_user_name' => $res['data']['user']['name']]);
            $this->clearLoginAttempts($request);
            return redirect()->to('/foradmin');
        }else{

            $this->validate($request,['errorRturn' => 'required'],[
                'errorRturn.required' => '账号或密码错误',
            ]);
            $this->incrementLoginAttempts($request);
            return redirect()->to('/foradmin/login');
        }
    }

    /**
     *退出登录
     */
    public function logout(Request $request)
    {
        $request->session()->invalidate();
        return redirect()->to(route('admin.login'));
    }

}